﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using EntityComponentSystem.Framework.Engine.Components;
using EntityComponentSystem.Framework.Engine;
using EntityComponentSystem.Framework.Engine.Entities;

namespace EntityComponentSystem.Demo.Aspects
{
    public interface IRenderComponent : IComponent
    {
        int Width { get; }
        int Height { get; }
        void SetSize(int width, int height);
    }

    public class RenderComponent : EntityComponentSystem.Framework.Engine.Components.Component, IRenderComponent
    {

        public int Width { get; private set; }
        public int Height { get; private set; }

        public void SetSize(int width, int height)
        {
            this.Width = width;
            this.Height = height;

        }

        public override void OnInit()
        {
        }

        public override void OnDispose()
        {
        }
    }

    public class RenderSystem : EntityComponentSystem.Framework.Engine.Systems.IntervalSystem<RenderComponent>
    {
        private bool flip = false;
        private Form form = null;

        public bool WaitForFormUpdate = false;
        public Bitmap Bitmap { get; private set; }
        public RenderSystem(IGameEngine ge, Form form)
            : base(ge)
        {
            this.form = form;
            Bitmap = new Bitmap(1000, 1000);
            using (var g = Graphics.FromImage(Bitmap))
                g.FillRectangle(Brushes.Black, 0, 0, 1000, 1000);

        }

        protected override void OnUpdate(long timeDelta, float timeDeltaF)
        {
            if (!WaitForFormUpdate)
            {
                //flip = !flip;
                flip = true;
                var ricochet = GameEngine.FindSystem<RicochetSystem>();
                if (ricochet != null)
                {
                    using (var g = Graphics.FromImage(Bitmap))
                    {
                        foreach (var r in ricochet.AllComponents)
                        {
                            g.FillRectangle(flip ? Brushes.White : Brushes.Black, r.Position.X, r.Position.Y, 1, 1);
                        }
                    }
                }
                WaitForFormUpdate = true;
                form.Invalidate();
            }
        }

        protected override void OnAddEntity(Entity e, RenderComponent com)
        {
        }

        protected override void OnRemoveEntity(Entity e, RenderComponent com)
        {
        }

        protected override void OnDispose()
        {
        }
    }

}
